package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.model.CurrentUser;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.UserContext;
import com.jzo2o.customer.enums.CertificationStatusEnum;
import com.jzo2o.customer.mapper.AgencyCertificationMapper;
import com.jzo2o.customer.mapper.RejectReasonMapper;
import com.jzo2o.customer.model.domain.AgencyCertification;
import com.jzo2o.customer.model.domain.RejectReason;
import com.jzo2o.customer.model.dto.AgencyCertificationUpdateDTO;
import com.jzo2o.customer.model.dto.request.AuditWorkReqDto;
import com.jzo2o.customer.model.dto.request.InstitutionCertificationAuditAddReqDTO;
import com.jzo2o.customer.model.dto.request.InstitutionPageQueryParamsDTO;
import com.jzo2o.customer.model.dto.response.InstitutionCertificationAuditRespDTO;
import com.jzo2o.customer.service.IAgencyCertificationService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 机构认证信息表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-06
 */
@Service
public class AgencyCertificationServiceImpl extends ServiceImpl<AgencyCertificationMapper, AgencyCertification> implements IAgencyCertificationService {

   @Resource
   private RejectReasonMapper rejectReasonMapper;
    /**
     * 根据机构id更新
     *
     * @param agencyCertificationUpdateDTO 机构认证更新模型
     */
    @Override
    public void updateByServeProviderId(AgencyCertificationUpdateDTO agencyCertificationUpdateDTO) {
        LambdaUpdateWrapper<AgencyCertification> updateWrapper = Wrappers.<AgencyCertification>lambdaUpdate()
                .eq(AgencyCertification::getId, agencyCertificationUpdateDTO.getId())
                .set(AgencyCertification::getCertificationStatus, agencyCertificationUpdateDTO.getCertificationStatus())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getName()), AgencyCertification::getName, agencyCertificationUpdateDTO.getName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getIdNumber()), AgencyCertification::getIdNumber, agencyCertificationUpdateDTO.getIdNumber())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonName()), AgencyCertification::getLegalPersonName, agencyCertificationUpdateDTO.getLegalPersonName())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getLegalPersonIdCardNo()), AgencyCertification::getLegalPersonIdCardNo, agencyCertificationUpdateDTO.getLegalPersonIdCardNo())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getBusinessLicense()), AgencyCertification::getBusinessLicense, agencyCertificationUpdateDTO.getBusinessLicense())
                .set(ObjectUtil.isNotEmpty(agencyCertificationUpdateDTO.getCertificationTime()), AgencyCertification::getCertificationTime, agencyCertificationUpdateDTO.getCertificationTime());
        super.update(updateWrapper);
    }

    @Override
    public void add(InstitutionCertificationAuditAddReqDTO institutionRegistrReqDTO) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long id = currentUser.getId();
        AgencyCertification byId = getById(id);
        if (byId != null) {
            //更新
            AgencyCertification bean = BeanUtil.toBean(institutionRegistrReqDTO, AgencyCertification.class);
            bean.setId(id);
            bean.setCertificationTime(null);
            bean.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
            boolean updateById = updateById(bean);
            if (!updateById) {
                throw new RuntimeException("更新认证信息失败");
            }
            RejectReason rejectReason = new RejectReason();
            rejectReason.setWorkInstitutionId(id);
            rejectReason.setCertificationStatus(bean.getCertificationStatus());
            rejectReasonMapper.insert(rejectReason);
            return;
        }
        AgencyCertification bean = BeanUtil.toBean(institutionRegistrReqDTO, AgencyCertification.class);
        bean.setCertificationStatus(CertificationStatusEnum.PROGRESSING.getStatus());
        bean.setId(id);
        boolean save = save(bean);
        if(!save) {
            throw new RuntimeException("保存机构认证信息失败");
        }
        RejectReason rejectReason = new RejectReason();
        rejectReason.setWorkInstitutionId(id);
        rejectReason.setCertificationStatus(bean.getCertificationStatus());
        rejectReasonMapper.insert(rejectReason);
    }
    @Override
    public String queryNewRejectReason() {
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long id = currentUser.getId();
        //查询拒绝原因表来查询最新的拒绝原因
        LambdaQueryWrapper<RejectReason> rejectReasonLambdaQueryWrapper = Wrappers.<RejectReason>lambdaQuery()
                .eq(RejectReason::getWorkInstitutionId, id)
                .orderByAsc(RejectReason::getCertificationTime);
        List<RejectReason> rejectReasons = rejectReasonMapper.selectList(rejectReasonLambdaQueryWrapper);
        if (ObjectUtil.isNotEmpty(rejectReasons)) {
            return rejectReasons.get(0).getRejectReason();
        }
        return "";
    }

    @Override
    public PageResult<InstitutionCertificationAuditRespDTO> pageQueryAgency(InstitutionPageQueryParamsDTO institutionStaffPageQueryReqDTO) {
        PageResult<InstitutionCertificationAuditRespDTO> page = PageHelperUtils.selectPage(institutionStaffPageQueryReqDTO, () -> baseMapper.queryWorkerList(institutionStaffPageQueryReqDTO));
      return page;
    }

    @Override
    public void auditInstitution(Long id, AuditWorkReqDto auditWorkReqDto) {
        CurrentUser currentUser = UserContext.getCurrentUser();
        Long auditorId = currentUser.getId();
        String auditorName = currentUser.getName();
        int certificationStatus = auditWorkReqDto.getCertificationStatus();
        if (certificationStatus == CertificationStatusEnum.FAIL.getStatus()){
            AgencyCertification agencyCertification = baseMapper.selectById(id);
            agencyCertification.setCertificationStatus(auditWorkReqDto.getCertificationStatus());
            agencyCertification.setCertificationTime(LocalDateTime.now());
            updateById(agencyCertification);
            LambdaQueryWrapper<RejectReason> eq = Wrappers.<RejectReason>lambdaQuery().eq(RejectReason::getWorkInstitutionId, id).eq(RejectReason::getAuditStatus, 0);
            RejectReason rejectReason = rejectReasonMapper.selectOne(eq);
            rejectReason.setRejectReason(auditWorkReqDto.getRejectReason());
            rejectReason.setAuditStatus(1);
            rejectReason.setAuditorName(auditorName);
            rejectReason.setAuditorId(auditorId);
            rejectReason.setCertificationStatus(auditWorkReqDto.getCertificationStatus());
            rejectReasonMapper.updateById(rejectReason);
            return;
        }
        AgencyCertification agencyCertification = baseMapper.selectById(id);
        agencyCertification.setCertificationStatus(auditWorkReqDto.getCertificationStatus());
        agencyCertification.setCertificationTime(LocalDateTime.now());
        updateById(agencyCertification);
        LambdaQueryWrapper<RejectReason> eq = Wrappers.<RejectReason>lambdaQuery().eq(RejectReason::getWorkInstitutionId, id).eq(RejectReason::getAuditStatus, 0);
        RejectReason rejectReason = rejectReasonMapper.selectOne(eq);
        rejectReason.setRejectReason(auditWorkReqDto.getRejectReason());
        rejectReason.setAuditStatus(1);
        rejectReason.setAuditorName(auditorName);
        rejectReason.setAuditorId(auditorId);
        rejectReason.setCertificationStatus(auditWorkReqDto.getCertificationStatus());
        rejectReasonMapper.updateById(rejectReason);
    }


}
